import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { apiClient } from '@/config/api'

// 从环境变量读取API基础地址（带容错处理）
function buildApiBaseUrl(): string {
  const host = import.meta.env.VITE_BACKEND_HOST || 'localhost'
  const port = import.meta.env.VITE_BACKEND_PORT || '806'
  
  if (!host || host === 'undefined' || host === 'null') {
    console.warn('⚠️ VITE_BACKEND_HOST 未配置，使用默认值: localhost')
    return `http://localhost:${port}`
  }
  
  if (!port || port === 'undefined' || port === 'null') {
    console.warn('⚠️ VITE_BACKEND_PORT 未配置，使用默认值: 806')
    return `http://${host}:806`
  }
  
  return `http://${host}:${port}`
}

const API_BASE_URL = buildApiBaseUrl()

export interface ModelConfig {
  id?: string
  name: string
  provider: string
  model: string
  apiKey: string
  apiUrl: string
  parameters: {
    temperature: string | number
    maxTokens: number
    topP?: string | number
  }
  frequencyPenalty?: string | number
  presencePenalty?: string | number
  systemPrompt?: string | null
  isActive: boolean
  isDefault?: boolean
  settings?: any
  userId?: string | null
  createdAt?: string
  updatedAt?: string
  // 为了向后兼容，保留这些字段
  baseUrl?: string
  temperature?: number
  maxTokens?: number
}

export interface ModelConfigResponse {
  success: boolean
  data: {
    configs: ModelConfig[]
    total: number
  }
  message?: string
}

export const useModelConfigStore = defineStore('modelConfig', () => {
  // 状态
  const configs = ref<ModelConfig[]>([])
  const isLoaded = ref(false)
  const isLoading = ref(false)
  
  // 默认配置模板
  const defaultConfigTemplates = {
    openai: {
      name: 'OpenAI GPT',
      provider: 'openai',
      model: 'gpt-3.5-turbo',
      apiKey: '',
      baseUrl: 'https://api.openai.com/v1',
      temperature: 0.7,
      maxTokens: 1000,
      isActive: false
    },
    claude: {
      name: 'Anthropic Claude',
      provider: 'claude',
      model: 'claude-3-sonnet-20240229',
      apiKey: '',
      baseUrl: 'https://api.anthropic.com',
      temperature: 0.7,
      maxTokens: 1000,
      isActive: false
    },
    qwen: {
      name: '阿里云通义千问',
      provider: 'qwen',
      model: 'qwen-turbo',
      apiKey: '',
      baseUrl: 'https://dashscope.aliyuncs.com/api/v1',
      temperature: 0.7,
      maxTokens: 1000,
      isActive: false
    },
    deepseek: {
      name: 'DeepSeek',
      provider: 'deepseek',
      model: 'deepseek-chat',
      apiKey: '',
      baseUrl: 'https://api.deepseek.com/chat/completions',
      temperature: 0.7,
      maxTokens: 2048,
      isActive: false
    }
  }

  // 计算属性
  const enabledConfigs = computed(() => {
    return configs.value.filter(config => config.isActive)
  })

  const hasEnabledConfigs = computed(() => enabledConfigs.value.length > 0)
  
  const defaultConfig = computed(() => {
    return configs.value.find(config => config.isDefault)
  })

  const availableModels = computed(() => {
    return configs.value.filter(config => config.isActive)
  })

  // 方法
  const loadConfigs = async () => {
    if (isLoading.value) return
    
    try {
      isLoading.value = true
      
      // 检查环境变量（用于调试）
      console.log('🔍 环境变量检查:', {
        VITE_BACKEND_HOST: import.meta.env.VITE_BACKEND_HOST,
        VITE_BACKEND_PORT: import.meta.env.VITE_BACKEND_PORT,
        VITE_API_BASE_URL: import.meta.env.VITE_API_BASE_URL,
        NODE_ENV: import.meta.env.MODE,
        apiClient_baseURL: apiClient.defaults.baseURL
      })
      
      // 发送请求（URL 验证已在 apiClient 拦截器中处理）
      const response = await apiClient.get('/ai-config')
      
      const result = response.data
      
      if (result.success) {
        // 后端返回的数据结构是 { data: { configs: [...], total: number } }
        // 需要映射到前端期望的格式
        configs.value = result.data.configs || []
      } else {
        console.error('获取配置失败:', result.message)
        configs.value = []
      }
      
      isLoaded.value = true
    } catch (error) {
      console.error('加载配置失败:', error)
      configs.value = []
      isLoaded.value = true
    } finally {
      isLoading.value = false
    }
  }

  const saveConfig = async (config: ModelConfig) => {
    try {
      const isUpdate = !!config.id
      const url = isUpdate 
        ? `/ai-config/${config.id}`
        : '/ai-config'
      
      const requestData = {
        name: config.name,
        provider: config.provider,
        model: config.model,
        apiUrl: config.baseUrl || config.apiUrl,
        apiKey: config.apiKey,
        parameters: {
          temperature: config.temperature,
          maxTokens: config.maxTokens
        },
        isActive: config.isActive,
        isDefault: config.isDefault || false
      }
      
      const response = isUpdate 
        ? await apiClient.put(url, requestData)
        : await apiClient.post(url, requestData)
      
      const result = response.data
      
      if (result.success) {
        // 更新本地配置列表
        if (isUpdate) {
          const index = configs.value.findIndex(c => c.id === config.id)
          if (index !== -1) {
            configs.value[index] = { ...config, ...result.data }
          }
        } else {
          configs.value.push(result.data)
        }
        return { success: true, message: isUpdate ? '配置更新成功' : '配置创建成功' }
      } else {
        return { success: false, message: result.message || '保存配置失败' }
      }
    } catch (error: any) {
      console.error('保存配置失败:', error)
      const message = error.response?.data?.error?.message || error.message || '保存配置时发生错误'
      return { success: false, message }
    }
  }

  const testConnection = async (config: ModelConfig) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/ai-config/test`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          provider: config.provider,
          model: config.model,
          baseUrl: config.baseUrl,
          apiKey: config.apiKey,
          parameters: {
            temperature: config.temperature,
            max_tokens: config.maxTokens
          }
        })
      })
      
      const result = await response.json()
      
      if (response.ok && result.success) {
        return { success: true }
      } else {
        return { success: false, message: result.message || '连接测试失败' }
      }
    } catch (error) {
      console.error('测试连接失败:', error)
      return { success: false, message: '测试连接失败，请检查网络连接' }
    }
  }

  const getModelConfig = (modelId: string) => {
    return configs.value.find(config => config.id === modelId) || null
  }

  const deleteConfig = async (configId: string) => {
    try {
      const response = await apiClient.delete(`/ai-config/${configId}`)
      const result = response.data
      
      if (result.success) {
        // 从本地配置列表中移除
        configs.value = configs.value.filter(config => config.id !== configId)
        return { success: true, message: '配置删除成功' }
      } else {
        return { success: false, message: result.message || '删除配置失败' }
      }
    } catch (error: any) {
      console.error('删除配置失败:', error)
      const message = error.response?.data?.error?.message || error.message || '删除配置时发生错误'
      return { success: false, message }
    }
  }

  const createConfigFromTemplate = (provider: string) => {
    const template = (defaultConfigTemplates as Record<string, any>)[provider]
    if (!template) {
      throw new Error(`未找到 ${provider} 的配置模板`)
    }
    return { ...template }
  }

  return {
    configs,
    isLoaded,
    isLoading,
    enabledConfigs,
    hasEnabledConfigs,
    defaultConfig,
    availableModels,
    defaultConfigTemplates,
    loadConfigs,
    saveConfig,
    testConnection,
    getModelConfig,
    deleteConfig,
    createConfigFromTemplate
  }
})